package com.itheima.web.controller.message;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.message.Communication;
import com.itheima.domain.message.CommunicationExample;
import com.itheima.domain.system.User;
import com.itheima.domain.system.UserPortrait;
import com.itheima.service.message.CommunicationService;
import com.itheima.service.system.UserProtraitService;
import com.itheima.service.system.UserService;
import com.itheima.vo.CommunicationVo;
import com.itheima.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/message")
public class CommunicationController extends BaseController {

    @Reference
    private CommunicationService communicationService;
    @Reference
    private UserService userService;
    @Reference
    private UserProtraitService userProtraitService;





    //    0  --  saas管理员 ---------能看所有
//        1  --  企业管理员 ---------能看自己公司的
//        4  --  普通员工--------------只能看自己的消息数据
    @RequestMapping(value = "/inboxList", name = "收件信息列表查询")
    public String inboxList(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {

        CommunicationExample communicationExample = new CommunicationExample();
        CommunicationExample.Criteria criteria = communicationExample.createCriteria();

        //细粒度权限控制条件加入
        Integer degree = getLoginUser().getDegree();
        if (degree == 0) {//saas管理员能看所有
            communicationExample.setOrderByClause("create_time desc");//按照创建日期排序

        } else if (degree == 1) {//企业管理员--------------本公司所有员工的合同数据
            criteria.andCompanyIdEqualTo(getCompanyId());
            communicationExample.setOrderByClause("create_time desc");//按照创建日期排序
        } else {//普通员工--------------只能看自己的
            criteria.andRecipientIdEqualTo(getLoginUser().getId());
            criteria.andRecipientStateEqualTo("0");
            communicationExample.setOrderByClause("recipient_top desc,state asc,create_time desc");//按照重要程度、已读未读、创建日期排序
        }
        PageInfo pageInfo = communicationService.findByPage(pageNum, pageSize, communicationExample);
        request.setAttribute("page", pageInfo);

        return "message/inbox/inbox-list";
    }
    @RequestMapping(value = "/outboxList", name = "发件信息列表查询")
    public String outboxList(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {

        CommunicationExample communicationExample = new CommunicationExample();
        CommunicationExample.Criteria criteria = communicationExample.createCriteria();

        //细粒度权限控制条件加入
        Integer degree = getLoginUser().getDegree();
        if (degree == 0) {//saas管理员能看所有
            communicationExample.setOrderByClause("create_time desc");//按照创建日期排序

        } else if (degree == 1) {//企业管理员--------------本公司所有员工的合同数据
            criteria.andCompanyIdEqualTo(getCompanyId());
            communicationExample.setOrderByClause("create_time desc");//按照创建日期排序
        } else {//普通员工--------------只能看自己的
            criteria.andSenderIdEqualTo(getLoginUser().getId());
            criteria.andSenderStateEqualTo("0");
            communicationExample.setOrderByClause("sender_top desc,create_time desc");//按照重要程度、已读未读、创建日期排序
        }
        PageInfo pageInfo = communicationService.findByPage(pageNum, pageSize, communicationExample);
        request.setAttribute("page", pageInfo);

        return "message/outbox/outbox-list";
    }


    @RequestMapping(value = "/toSendMessage", name = "跳转发消息界面")
    public String toSendMessage() {
        return "message/outbox/outbox-send";
    }

    @RequestMapping(value = "/toReply", name = "跳转回复消息界面")
    public String toReply(String id) {
        Communication communication = communicationService.findById(id);
        request.setAttribute("communication",communication);
        ArrayList<Communication> arrayList = new ArrayList<>();
        listAdd(communication,arrayList);
        Collections.reverse(arrayList);
        request.setAttribute("arrayList",arrayList);
        return "message/inbox/inbox-reply";
    }

    @RequestMapping(value = "/toForward", name = "跳转转发消息界面")
    public String toForward(String id) {
        Communication communication = communicationService.findById(id);
        request.setAttribute("communication",communication);

        return "message/outbox/outbox-forward";
    }

    @ResponseBody
    @RequestMapping(value = "/title", name = "查找未读信息")
    public List<CommunicationVo> title() {
        List<CommunicationVo> listVo = new ArrayList<>();
        List<Communication> list = communicationService.findUnread(getLoginUser().getId());
        for (Communication communication : list) {
            CommunicationVo communicationVo = new CommunicationVo();
            BeanUtil.copyProperties(communication,communicationVo);
            long time = new Date().getTime() - communication.getSendTime().getTime();
            if (time / 1000 < 60) {
                communicationVo.setTime(time/1000+"秒钟之前");
            } else if (time / 1000 / 60 < 60) {
                communicationVo.setTime(time/1000/60+"分钟之前");
            } else if (time / 1000 / 60/60<24) {
                communicationVo.setTime(time/1000/60/60+"小时之前");
            } else  {
                communicationVo.setTime(time/1000/60/60/24+"天之前");
            }
            UserPortrait userPortrait = userProtraitService.selectByPrimaryKey(communication.getSenderId());
            String userProtrait = userPortrait.getUserProtrait();
            if (StringUtils.isEmpty(userProtrait)) {
                userProtrait = request.getContextPath()+"/img/user2-160x160.jpg";
            }
            communicationVo.setPath(userProtrait);
            listVo.add(communicationVo);
        }
        return listVo;
    }

    public void listAdd(Communication communication,ArrayList<Communication> list) {
        list.add(communication);
        if (StringUtils.isNoneEmpty(communication.getPid())) {
            Communication parentCommunication = communicationService.findById(communication.getPid());
            listAdd(parentCommunication,list);
        }
    }

    @RequestMapping(value = "/reply", name = "发消息")
    public String reply(Communication communication) {
        User user = userService.findByEmail(communication.getRecipientEmail());
        if (user == null) {
            request.setAttribute("error","收件人不存在！");
            return "message/outbox/outbox-send";
        }

            communication.setId(UUID.randomUUID().toString());
            //设置发件人信息
            communication.setSenderId(getLoginUser().getId());
            communication.setSender(getLoginUser().getUserName());
            communication.setSenderEmail(getLoginUser().getEmail());
            //设置收件人信息
            communication.setRecipientId(user.getId());
            communication.setRecipient(user.getUserName());
            //设置公司信息
            communication.setCompanyId(getCompanyId());
            communication.setCompanyName(getCompanyName());
            //创建者信息
            communication.setCreateBy(getLoginUser().getId());
            communication.setCreateDept(getLoginUser().getDeptId());
            Date date = new Date();
            communication.setCreateTime(date);
            //设置隐藏信息
            communication.setSenderState("0");
            communication.setRecipientState("0");
            //设置信件状态
            communication.setState("0");//未读
            //设置重要程度
            communication.setSenderTop("0");
            communication.setRecipientTop("0");
            //设置收发时间
            communication.setSendTime(date);
            communication.setReceivedTime(date);
            //保存信息到数据库
            communicationService.save(communication);

        return "redirect:/message/inboxList.do";
    }

    @RequestMapping(value = "/send", name = "发消息")
    public String send(Communication communication) {
        User user = userService.findByEmail(communication.getRecipientEmail());
        if (user == null) {
            request.setAttribute("error","收件人不存在！");
            return "message/outbox/outbox-send";
        }

            communication.setId(UUID.randomUUID().toString());
            //设置发件人信息
            communication.setSenderId(getLoginUser().getId());
            communication.setSender(getLoginUser().getUserName());
            communication.setSenderEmail(getLoginUser().getEmail());
            //设置收件人信息
            communication.setRecipientId(user.getId());
            communication.setRecipient(user.getUserName());
            //设置公司信息
            communication.setCompanyId(getCompanyId());
            communication.setCompanyName(getCompanyName());
            //创建者信息
            communication.setCreateBy(getLoginUser().getId());
            communication.setCreateDept(getLoginUser().getDeptId());
            Date date = new Date();
            communication.setCreateTime(date);
            //设置隐藏信息
            communication.setSenderState("0");
            communication.setRecipientState("0");
            //设置信件状态
            communication.setState("0");//未读
            //设置重要程度
            communication.setSenderTop("0");
            communication.setRecipientTop("0");
            //设置收发时间
            communication.setSendTime(date);
            communication.setReceivedTime(date);
            //保存信息到数据库
            communicationService.save(communication);

        return "redirect:/message/outboxList.do";
    }

    @RequestMapping(value = "/hiddenSend", name = "发件隐藏")
    public String hiddenSend(String id) {
        Communication communication = communicationService.findById(id);
        communication.setSenderState("1");
        communicationService.update(communication);
        return "redirect:/message/outboxList.do";
    }

    @RequestMapping(value = "/hiddenReceived", name = "收件隐藏")
    public String hiddenReceived(String id) {
        Communication communication = communicationService.findById(id);
        communication.setRecipientState("1");
        communicationService.update(communication);
        return "redirect:/message/inboxList.do";
    }

    @RequestMapping(value = "/toView", name = "跳转查看发送信息界面")
    public String toView(String id) {
        Communication communication = communicationService.findById(id);
        request.setAttribute("communication", communication);
        User sender = userService.findById(communication.getSenderId());
        User recipient = userService.findById(communication.getRecipientId());
        String senderDeptName = sender.getDeptName();
        String recipientDeptName = recipient.getDeptName();
        Map<String, String> dept = new HashMap<>();
        dept.put("senderDept", senderDeptName);
        dept.put("recipientDept", recipientDeptName);
        request.setAttribute("dept",dept);
        return "/message/outbox/outbox-view";
    }
    @RequestMapping(value = "/toInboxView", name = "跳转查看收件信息界面")
    public String toInboxView(String id) {
        Communication communication = communicationService.findById(id);
        request.setAttribute("communication", communication);
        User sender = userService.findById(communication.getSenderId());
        User recipient = userService.findById(communication.getRecipientId());
        String senderDeptName = sender.getDeptName();
        String recipientDeptName = recipient.getDeptName();
        Map<String, String> dept = new HashMap<>();
        dept.put("senderDept", senderDeptName);
        dept.put("recipientDept", recipientDeptName);
        request.setAttribute("dept",dept);

        if (getLoginUser().getId().equals(communication.getRecipientId())) {
            communication.setState("1");
            communicationService.update(communication);
        }
        return "/message/inbox/inbox-view";
    }

    @RequestMapping(value = "/topSend", name = "发件信息星标")
    public String topSend(String id) {
        Communication communication = communicationService.findById(id);
        communication.setSenderTop("1");
        communicationService.update(communication);
        return "redirect:/message/outboxList.do";
    }
    @RequestMapping(value = "/distopSend", name = "发件信息取消星标")
    public String distopSend(String id) {
        Communication communication = communicationService.findById(id);
        communication.setSenderTop("0");
        communicationService.update(communication);
        return "redirect:/message/outboxList.do";
    }
    @RequestMapping(value = "/topRecipient", name = "收件信息星标")
    public String topRecipient(String id) {
        Communication communication = communicationService.findById(id);
        communication.setRecipientTop("1");
        communicationService.update(communication);
        return "redirect:/message/inboxList.do";
    }
    @RequestMapping(value = "/distopRecipient", name = "收件信息取消星标")
    public String distopRecipient(String id) {
        Communication communication = communicationService.findById(id);
        communication.setRecipientTop("0");
        communicationService.update(communication);
        return "redirect:/message/inboxList.do";
    }

}
